//
//  UserProfileController.m
//  collection
//
//  Created by 靖 张 on 11/30/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "UserProfileController.h"
#import "UserWeiboTableHandler.h"
#import "UserFolloweeTableHandler.h"
#import "UserFollowerTableHandler.h"
#import "UserFavorTableHandler.h"
#import "MyInfoController.h"
#import "PrivateLetterItem.h"
#import "PrivateLetterContentController.h"
#import "CollectionDataManager.h"

@interface UserProfileController()

@property (nonatomic, strong)   IBOutlet    UIView*         tableHeaderView;
@property (nonatomic, strong)   IBOutlet    UITableView*    tableView;
@property (nonatomic, strong)   IBOutlet    UIButton*       actionButton;
@property (nonatomic, strong)   IBOutlet    UIBarButtonItem*    rightBarButton;
@property (retain, nonatomic) IBOutlet UIImageView *avatarView;
@property (retain, nonatomic) IBOutlet UILabel *nicknameLabel;
@property (retain, nonatomic) IBOutlet UILabel *signatureArea;
@property (retain, nonatomic) IBOutlet UIImageView *signatureAreaView;
@property (retain, nonatomic) IBOutlet UINavigationItem *navItem;

- (IBAction)onClickBackBarItem:(id)sender;
- (IBAction)onClickTabButton:(id)sender;
- (IBAction)onclickActionButton:(id)sender;
- (IBAction)onClickRightBarButton:(id)sender;

- (void)onTapSignatureArea:(UITapGestureRecognizer*)tapGestureRecognizer;
- (void)adjustHeaderView:(BOOL)signatureHasBgView action:(BOOL)toExpandSignatureArea;

@end

@implementation UserProfileController

@synthesize userID = _userID;
@synthesize tableHeaderView = _tableHeaderView;
@synthesize tableView = _tableView;
@synthesize actionButton    = _actionButton;
@synthesize rightBarButton  = _rightBarButton;
@synthesize avatarView = _avatarView;
@synthesize nicknameLabel = _nicknameLabel;
@synthesize signatureArea = _signatureArea;
@synthesize signatureAreaView = _signatureAreaView;
@synthesize navItem = _navItem;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.hidesBottomBarWhenPushed = YES;
        
        
    }
    
    return self;
}

- (void)dealloc {
    [_subTabHandler release];
    
    [_avatarView release];
    [_nicknameLabel release];
    [_signatureArea release];
    [_signatureAreaView release];
    [_navItem release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)loadView {
    
    [super loadView];
    
    if (self.navigationController == nil) {
        self.navItem.leftBarButtonItem = nil;
    }
    
    // Add four empty tabs
    UserWeiboTableHandler* weiboHandler = [[UserWeiboTableHandler alloc] init];
    weiboHandler.homepageRootController = self;
    weiboHandler.userID = self.userID;
    
    UserFolloweeTableHandler* followeeHandler = [[UserFolloweeTableHandler alloc] init];
    followeeHandler.homepageRootController = self;
    followeeHandler.userID = 1;
    
    UserFollowerTableHandler* followerHandler = [[UserFollowerTableHandler alloc] init];
    followerHandler.homepageRootController = self;
    followerHandler.userID = 1;
    
    UserFavorTableHandler* favorHandler = [[UserFavorTableHandler alloc] init];
    favorHandler.homepageRootController = self;
    
    CollectionDataManager* dataManager = [CollectionDataManager sharedInstance];
    UserInfo* loginUser = dataManager.currentLoginUser;
    if (loginUser.userID == self.userID) {
        _subTabHandler = [[NSArray alloc] initWithObjects:weiboHandler, followeeHandler, followerHandler, favorHandler, nil];
        self.rightBarButton.customView.hidden = YES;
    }
    else {
        _subTabHandler = [[NSArray alloc] initWithObjects:weiboHandler, followeeHandler, followerHandler, nil];
    }
    
    [weiboHandler release];
    [followeeHandler release];
    [followerHandler release];
    [favorHandler release];
    
    // Customize
    if (self.userID == loginUser.userID) {
        [self.actionButton setTitle:@"编辑" forState:UIControlStateNormal];
        [self.actionButton setTitle:@"编辑" forState:UIControlStateHighlighted];
    }
    else {
        [self.actionButton setTitle:@"私信" forState:UIControlStateNormal];
        [self.actionButton setTitle:@"私信" forState:UIControlStateHighlighted];
        
        UIButton* btn = (UIButton*)self.rightBarButton.customView;
        // Relation : follow
        if (NO) {
            [btn setTitle:@"取消关注" forState:UIControlStateNormal];
            [btn setTitle:@"取消关注" forState:UIControlStateHighlighted];
        }
        else {
            [btn setTitle:@"关注" forState:UIControlStateNormal];
            [btn setTitle:@"关注" forState:UIControlStateHighlighted];
        }
        
        UIButton* favorButton = (UIButton*)[self.tableHeaderView viewWithTag:14];
        favorButton.hidden = YES;
    }
    
    int tagNumber = (self.userID == loginUser.userID) ? 4 : 3;
    int width = self.view.frame.size.width / tagNumber;
    UIView* tabRegionView = [self.tableHeaderView viewWithTag:10];
    for (int i = 0; i < tagNumber; i++) {

        int tag = i + 11;
        UIButton* tabButton = (UIButton*)[tabRegionView viewWithTag:tag];

        CGRect frame = tabButton.frame;
        frame.origin.x = i * width + (width - frame.size.width) / 2;
        frame.origin.y = 0;
        frame.size.width = 75;
        frame.size.height = 50;
        tabButton.frame = frame;
        tabButton.titleLabel.numberOfLines = 0;
        tabButton.titleLabel.textAlignment = UITextAlignmentCenter;
        NSString* text = [NSString stringWithFormat:@"%@\n%d", tabButton.titleLabel.text, (tag * 10)];
        [tabButton setTitle:text forState:UIControlStateNormal];
        [tabButton setTitle:text forState:UIControlStateSelected];
    }
    
    // Switch to the "Weibo" tab
    [self setActiveSubTab:0];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    UserInfo* user = [sharedDataManager cacheUserByUserID:self.userID];
    if (user) {
        self.avatarView.image = user.avatar;
        self.nicknameLabel.text = user.nickname;
        self.signatureArea.text = user.signature;
        
        CGSize constraintSize = CGSizeMake(self.signatureArea.frame.size.width, 1000);
        CGSize size = [self.signatureArea.text sizeWithFont:self.signatureArea.font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap];
        if (size.height > 2 * 16) {
            
            UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapSignatureArea:)];
            tapGestureRecognizer.numberOfTapsRequired = 1;
            tapGestureRecognizer.numberOfTouchesRequired = 1;
            [self.signatureAreaView addGestureRecognizer:tapGestureRecognizer];
            [tapGestureRecognizer release];
            
            [self adjustHeaderView:YES action:NO];
        }
        else {
            
            [self adjustHeaderView:NO action:NO];
        }
    }
}

- (void)viewDidUnload
{
    [self setAvatarView:nil];
    [self setNicknameLabel:nil];
    [self setSignatureArea:nil];
    [self setSignatureAreaView:nil];
    [self setNavItem:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.tableHeaderView = nil;
    self.tableView = nil;
    self.actionButton = nil;
    self.rightBarButton = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Public methods

- (void)setActiveSubTab:(int)index {
    
    if (index < 0 || index >= [_subTabHandler count]) {
        return;
    }
    
    id handler = [_subTabHandler objectAtIndex:index];
    if (index == 0) {
        CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
        UserWeiboTableHandler* weiboHandler = (UserWeiboTableHandler*)handler;
        weiboHandler.dataList = sharedDataManager.feedList;
    }
    else if (index == 3) {
        CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
        UserFavorTableHandler* favorHandler = (UserFavorTableHandler*)handler;
        favorHandler.dataList = sharedDataManager.feedList;
    }
    
    self.tableView.dataSource = handler;
    self.tableView.delegate = handler;
    
    [self.tableView reloadData];
    
    // Change the active tab
    for (int tag = 11; tag <= 14; tag++) {
        UIButton* tabButton = (UIButton*)[self.tableHeaderView viewWithTag:tag];
        tabButton.selected = (tag == (index + 11));
    }
}

#pragma mark - Private methods

- (IBAction)onClickBackBarItem:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onClickTabButton:(id)sender {
    UIButton* button = (UIButton*)sender;
    
    int tag = button.tag;
    [self setActiveSubTab:(tag - 11)];
}

- (IBAction)onclickActionButton:(id)sender {
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    // Login user
    if (sharedDataManager.currentLoginUser.userID == self.userID) {
        UIViewController* myInfoController = [[MyInfoController alloc] initWithNibName:@"MyInfoController" bundle:nil];
        [self.navigationController pushViewController:myInfoController animated:YES];
        [myInfoController release];
    }
    // Other users
    else {
        NSDictionary* letterSet = sharedDataManager.privateLetterSet;
        long long userID = sharedDataManager.currentLoginUser.userID;
        NSArray* threads = [letterSet objectForKey:[NSString stringWithFormat:@"%lld", userID]];
        
        PrivateLetterThread* theThread = nil;
        for (PrivateLetterThread* oneThread in threads) {
            if (oneThread.objectID == self.userID) {
                theThread = oneThread;
                break;
            }
        }
        
        if (theThread == nil) {
            
        }
        
        PrivateLetterContentController* letterContentController = [[PrivateLetterContentController alloc] initWithNibName:@"PrivateLetterContentController" bundle:nil];
        letterContentController.conversationObjectUID = self.userID;//theThread.objectID;
        
        [self.navigationController pushViewController:letterContentController animated:YES];
        [letterContentController release];
    }
}

- (IBAction)onClickRightBarButton:(id)sender {
    
    CollectionDataManager* dataManager = [CollectionDataManager sharedInstance];
    UserInfo* loginUser = dataManager.currentLoginUser;
    if (loginUser.userID == self.userID) {
        return;
    }
    
    UIButton* btn = (UIButton*)sender;
    NSString* title = [btn titleForState:UIControlStateNormal];
    if ([title isEqualToString:@"关注"]) {
        [btn setTitle:@"取消关注" forState:UIControlStateNormal];
    }
    else {
        [btn setTitle:@"关注" forState:UIControlStateNormal];
    }
}

- (void)onTapSignatureArea:(UITapGestureRecognizer *)tapGestureRecognizer {
    
    static BOOL isExpand = NO;
    
    if (isExpand == NO) {
        [self adjustHeaderView:YES action:YES];
    }
    else {
        [self adjustHeaderView:YES action:NO];
    }
    
    isExpand = !isExpand;
}

- (void)adjustHeaderView:(BOOL)signatureHasBgView action:(BOOL)toExpandSignatureArea {
    
    CGSize constraintSize = CGSizeMake(self.signatureArea.frame.size.width, 1000);
    CGSize size = [self.signatureArea.text sizeWithFont:self.signatureArea.font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap];
    
    CGRect frame;
    
    frame = self.signatureArea.frame;
    if (signatureHasBgView == NO) {
        frame.size.height = size.height;
    }
    else if (toExpandSignatureArea) {
        frame.size.height = size.height;
    }
    else {
        frame.size.height = 2 * 16;
    }
    
    self.signatureArea.frame = frame;
    
    if (signatureHasBgView) {
        self.signatureAreaView.hidden = NO;
        
        CGRect bgFrame = frame;
        bgFrame.origin.x -= 5;
        bgFrame.origin.y -= 3;
        bgFrame.size.width += 10;
        bgFrame.size.height += 8;
        self.signatureAreaView.frame = bgFrame;
        UIImage* bgImage = nil;
        if (toExpandSignatureArea) {
            bgImage = [[UIImage imageNamed:@"person_info_2_bg"] stretchableImageWithLeftCapWidth
             :0 topCapHeight:15];
        }
        else {
            bgImage = [[UIImage imageNamed:@"person_info_bg"] stretchableImageWithLeftCapWidth
             :0 topCapHeight:15];
        }
        self.signatureAreaView.image = bgImage;
    }
    else {
        self.signatureAreaView.hidden = YES;
    }
    
    UIView* tabRegionView = [self.tableHeaderView viewWithTag:10];
    frame = tabRegionView.frame;
    frame.origin.y = self.signatureArea.frame.origin.y + self.signatureArea.frame.size.height + 9;
    tabRegionView.frame = frame;
    
    frame = self.tableHeaderView.frame;
    frame.size.height = tabRegionView.frame.origin.y + tabRegionView.frame.size.height;
    self.tableHeaderView.frame = frame;
    
    self.tableView.tableHeaderView = self.tableHeaderView;
}

@end
